<template>
  <div>
    <a-modal v-model="visible" centered title="新增账号" width="60vw" @ok="handleOk" @cancel="handleClose" :destroyOnClose="true" class="addbox">
      <div class="table-page-search-wrapper">
        <a-form layout="inline" @keyup.enter.native="search">
          <a-row :gutter="48">
            <a-col :md="6" :sm="24">
              <a-form-item style="display: flex">
                <div style="display: flex">
                  <a-select v-model="query.searchType" placeholder="请选择" style="width: 150px">
                    <a-select-option v-for="(item, index) in searchTypeList" :key="index" :value="item.type">{{ item.name }}</a-select-option>
                  </a-select>
                  <a-input v-model="query.searchValue" placeholder="请输入" style="margin-left: 5px" />
                </div>
              </a-form-item>
            </a-col>
            <a-col :md="4" :sm="24">
              <span class="table-page-search-submitButtons" :style="{ float: 'right', overflow: 'hidden' }">
                <a-button type="primary" @click="search" style="margin-right: 24px">搜索</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <s-table ref="table" size="default" bordered :rowKey="record => record.id" :columns="columns" :data="loadData" :rowSelection="rowSelection" :pagination="pagination">
        <span slot="serial" slot-scope="text, record, index">
          {{ (pagination.current - 1) * pagination.pageSize + index + 1 }}
        </span>
      </s-table>
      <div class="select-box">
        <span>角色：</span>
        <a-select v-model="roleListId" placeholder="多选" show-search style="width: 70%" mode="multiple">
          <a-select-option v-for="(item, index) in roleList" :key="index" :value="item.id">{{ item.name }}</a-select-option>
        </a-select>
      </div>
    </a-modal>
  </div>
</template>
<script>
import { STable } from '@/views/box/components'
import { roleList, addUserList, userListAddRole, editUserRole } from '@/api/pos/authority'
const columns = [
  {
    title: '姓名',
    align: 'center',
    dataIndex: 'realname'
  },
  {
    title: '工号',
    align: 'center',
    dataIndex: 'workNo'
  },
  {
    title: '账号',
    align: 'center',
    dataIndex: 'username'
  },
  {
    title: '手机号',
    align: 'center',
    dataIndex: 'phone'
  }
]
export default {
  components: {
    STable
  },
  data() {
    return {
      columns,
      visible: false,
      searchTypeList: [
        { type: 'employeeName', name: '姓名' },
        { type: 'workNo', name: '工号' },
        { type: 'phone', name: '手机号' },
        { type: 'username', name: '账号' }
      ],
      query: {
        searchType: 'workNo'
      },
      queryParam: {},
      roleCode: undefined,
      loadData: parameter => this.fetchData(parameter),
      pagination: {
        total: 0,
        showTotal: total => `共有 ${total} 条数据`
      },
      roleList: [],
      selectedRowKeys: [],
      roleListId: [],
      selectedRows: []
    }
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange,
        onSelect: this.onSelect,
        onSelectAll: this.onSelectAll
      }
    }
  },
  mounted() {
    this.getRoleList()
  },
  methods: {
    // 获取新增角色列表——均为启用状态
    getRoleList() {
      let params = {
        current: 1,
        size: 100,
        status: 'Y'
      }
      roleList(params).then(res => {
        if (res.code == 200) {
          this.roleList = res.data.records
        }
      })
    },
    // 关闭
    handleClose() {
      this.visible = false
      this.query = {}
      this.queryParam = {}
      this.roleListId = []
      this.selectedRows = []
      this.selectedRowKeys = []
    },
    // 新增账号
    async handleOk() {
      if (this.selectedRows.length == 0) {
        this.$toast('请选择需要添加的人员')
        return
      }
      if (this.roleListId.length == 0) {
        this.$toast('请选择需要添加的角色')
        return
      }
      let selectedList = this.selectedRows.map(item => {
        let result = {
          employeeId: item.id,
          employeeName: item.realname,
          phone: item.phone,
          workNo: item.workNo,
          account: item.username
        }
        return result
      })
      let param = {
        roleIds: this.roleListId.join(','),
        employeeList: selectedList
      }
      const res = await editUserRole(param)
      if (res.code == 200) {
        this.visible = false
        this.query = {}
        this.queryParam = {}
        this.roleListId = []
        this.selectedRows = []
        this.selectedRowKeys = []
        this.$emit('updataTable')
      } else {
        this.$message.error(res.msg || res.message)
      }
    },
    search() {
      let param = {}
      if (this.query.searchType == 'employeeName') {
        Object.assign(param, {
          realname: '*' + this.query.searchValue + '*'
        })
      } else if (this.query.searchType == 'workNo') {
        Object.assign(param, {
          workNo: this.query.searchValue
        })
      } else if (this.query.searchType == 'phone') {
        Object.assign(param, {
          phone: this.query.searchValue
        })
      } else if (this.query.searchType == 'username') {
        Object.assign(param, {
          username: this.query.searchValue
        })
      }
      this.queryParam = param
      this.$refs.table.refresh()
    },
    onChange(value) {
      this.roleCode = value
    },
    onSelect(record, selected, selectedRows) {
      selected ? this.selectedRows.push(record): this.selectedRows.splice(this.selectedRows.findIndex(x => x.id === record.id),1)
    },
    onSelectAll(selected, selectedRows, changeRows) {
      this.selectedRows = selected ?
          this.selectedRows.concat(changeRows) :
          this.selectedRows.filter(x => !changeRows.find(i => i.id === x.id))
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.$nextTick(()=>{
        this.selectedRowKeys = selectedRowKeys
      })
    },
    fetchData(parameter) {
      const queryParam = JSON.parse(JSON.stringify(this.queryParam))
      const data = {}
      data.addUserListQto = queryParam

      data.addUserListQto.pageNo = parameter.pageNo
      data.addUserListQto.pageSize = parameter.pageSize
      return userListAddRole(data.addUserListQto).then(res => {
        if (res.code === 0) {
          let result = res.result

          this.pagination.current = result.current
          const { total, size, current } = result
          const data = {
            page: {
              count: total,
              pageNo: current,
              pageSize: size,
              pages: Math.ceil(total / size)
            },
            data: result.records
          }
          return data
        } else {
          this.$message.error(res.msg || res.message)
          const data = {
            page: {
              pageNo: 0,
              count: 0,
              pageSize: 10
            },
            data: []
          }
          return data
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.addbox {
  height: 60vh;
}
.select-box {
  display: flex;
  margin: 30px 0;
}
</style>